package com.dragon.pear.common.spring.security;

import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtException;
import org.springframework.security.oauth2.jwt.JwtValidationException;

import java.time.Instant;
import java.util.Collections;

/**
 * 自定义JWT解码器
 */
public class CustomJwtDecoder implements JwtDecoder {
    private final JwtDecoder delegate;

    public CustomJwtDecoder(JwtDecoder delegate) {
        this.delegate = delegate;
    }

    @Override
    public Jwt decode(String token) throws JwtException {
        System.out.println("token: " + token);
        Jwt jwt = delegate.decode(token);
        validateToken(jwt);
        return jwt;
    }

    /**
     * 自定义JWT校验
     *
     * @param jwt
     */
    private void validateToken(Jwt jwt) {
        // 过期校验
        if (jwt.getExpiresAt() != null && Instant.now().isAfter(jwt.getExpiresAt())) {
            throw new JwtValidationException("Token过期",
                    Collections.singletonList(
                            new OAuth2Error(
                                    "invalid_token",
                                    "Token expired at " + jwt.getExpiresAt(),
                                    "https://tools.ietf.org/html/rfc6750#section-3.1"
                            )
                    )
            );
        }

        // 示例2：校验自定义声明
//        if (!"v2".equals(jwt.getClaim("token_version"))) {
//            throw new JwtValidationException("无效Token版本",
//                    Collections.singletonList(
//                            new OAuth2Error(
//                                    "invalid_token",
//                                    "Required token_version=v2",
//                                    null
//                            )
//                    )
//            );
//        }
    }
}